<template>
  <n-list>
    <n-list-item v-for="item in list" :key="item.id">
      <template #suffix>
        <n-upload
          :max="1"
          @before-upload="beforeUpload"
          :custom-request="
            ({ file }) => uploadFile({ file, id: item.id, _item: item })
          "
          :show-file-list="false"
        >
          <n-button
            type="primary"
            v-if="
              inProfile && isSelf && !item?.file?.fid && item.type != 'PROJECT'
            "
            >添加附件</n-button
          >
        </n-upload>
        <n-button
          type="primary"
          v-if="
            inProfile && !isSelf && !item?.file?.fid && item.type != 'PROJECT'
          "
          @click="askFile(item.id)"
          >申请附件</n-button
        >
        <n-button
          type="primary"
          v-if="inProfile && item?.file?.fid && item.type != 'PROJECT'"
          @click="checkFile(item.file.url)"
          >查看附件</n-button
        ><n-button
          type="primary"
          v-if="item.type == 'PROJECT'"
          :disabled="item.isMember"
          @click="apply(item.id)"
        >
          {{ item.isMember ? '已是成员' : '申请加入' }}
        </n-button>
      </template>
      <n-thing>
        <div>
          <n-ellipsis :line-clamp="1" :tooltip="false">
            <n-text
              class="text-xl font-semibold"
              style="cursor: pointer"
              @click="checkDetail(item.id)"
              v-if="item.type != 'PROJECT'"
              >{{ item.title }}
            </n-text>
            <n-text class="text-xl font-semibold" v-else
              >{{ item.title }}
            </n-text>
          </n-ellipsis>
        </div>
        <n-time :time="new Date(item.create_time)" type="datetime" />
        <div class="mb-2 mt-2" v-if="item.type != 'PROJECT'">
          <n-tag :bordered="false" type="warning" class="mr-3">
            {{ TYPE[item.type] }}
          </n-tag>
          <n-text depth="3">
            {{ item.date.year }}{{ item.date.month ? `-${item.date.month}` : ''
            }}{{ item.date.day ? `-${item.date.day}` : '' }}
          </n-text>
        </div>
        <div class="mb-2 mt-2" v-if="item.type == 'PROJECT'">
          <n-ellipsis :line-clamp="3">
            <n-tag :bordered="false" type="warning" class="mr-3"> 项目 </n-tag>
            <n-text depth="3">
              {{ item.goal }}
            </n-text>
          </n-ellipsis>
        </div>
        <div class="flex flex-wrap" v-if="item.type != 'PROJECT'">
          <div
            v-for="(_item, _index) in item.authors.slice(0, 4)"
            :key="_index"
            class="flex item-center mr-2 mb-1"
          >
            <n-text depth="2" class="mr-2" v-if="_index !== 0">·</n-text>
            <n-avatar
              round
              :size="20"
              :src="_item.avatar"
              class="mr-1"
              v-if="_item.isUser"
            />
            <!-- 用户信息 -->
            <n-popover
              trigger="hover"
              placement="bottom"
              :disabled="!_item.isUser"
              @update:show="(value) => handleAuthorInfoShow(value, _item.id)"
            >
              <template #trigger>
                <n-text depth="2">{{ _item.name }}</n-text>
              </template>
              <div class="grid grid-cols-4 p-3" v-show="authorInfo !== null">
                <div class="col-span-3">
                  <div class="font-semibold text-xl">
                    <n-ellipsis style="max-width: 200px">
                      <n-text
                        style="cursor: pointer"
                        @click="checkAuthor(_item.id)"
                        >{{ authorInfo?.name }}</n-text
                      >
                    </n-ellipsis>
                  </div>
                  <div>
                    <n-ellipsis style="max-width: 200px">
                      <n-text depth="2"
                        >{{ authorInfo?.degree
                        }}{{
                          authorInfo?.degree && authorInfo?.position
                            ? ` · ${authorInfo?.position}`
                            : ''
                        }}</n-text
                      >
                    </n-ellipsis>
                  </div>
                  <div class="text-gray-400 font-semibold text-sm mt-2">
                    机构
                  </div>
                  <div>
                    <n-ellipsis style="max-width: 200px">
                      <n-text depth="2">{{ authorInfo?.institution }}</n-text>
                    </n-ellipsis>
                  </div>
                  <div class="text-gray-400 font-semibold text-sm mt-2">
                    部门
                  </div>
                  <div>
                    <n-ellipsis style="max-width: 200px">
                      <n-text depth="2">{{ authorInfo?.department }}</n-text>
                    </n-ellipsis>
                  </div>
                  <div class="text-gray-400 font-semibold text-sm mt-2">
                    领域
                  </div>
                  <div>
                    <n-ellipsis style="max-width: 200px">
                      <n-text depth="2">{{ authorInfo?.field }}</n-text>
                    </n-ellipsis>
                  </div>
                </div>
                <n-avatar round :size="70" :src="authorInfo?.avatar" />
                <div class="flex justify-end col-span-4 mt-2">
                  <n-button
                    size="small"
                    type="primary"
                    class="follow-btn"
                    @click="changeFollow"
                  >
                    {{ authorInfo?.isFollowing ? '取消关注' : '关注' }}
                  </n-button>
                  <n-button size="small" @click="toChat"> 私信 </n-button>
                </div>
              </div>
            </n-popover>
          </div>
          <n-text depth="2" v-if="item.authors.length > 5">等</n-text>
        </div>
      </n-thing>
    </n-list-item>
  </n-list>
</template>

<script setup>
import api from '@/api/api'

const props = defineProps(['rawList', 'isSelf'])
const router = useRouter()

const message = useMessage()

const TYPE = {
  JOUR: '期刊论文',
  CPAPER: '会议论文',
  DATA: '数据',
  PROJECT: '项目'
}

const list = ref([])
const inProfile = typeof props.rawList !== 'undefined'

onMounted(() => {
  if (inProfile) {
    list.value = props.rawList
  }
})

watch(
  () => props.rawList,
  () => {
    if (inProfile) {
      list.value = props.rawList
    }
  }
)

const authorInfo = ref(null)
const tmpUid = ref('')

// 作者信息显示回调
const handleAuthorInfoShow = (value, id) => {
  if (value) {
    tmpUid.value = id
    authorInfo.value = null
    api.User.getProfile({ id }).then((res) => {
      authorInfo.value = res.data
    })
  }
}

// 修改关注状态
const changeFollow = () => {
  api.User.changeFollow({
    id: tmpUid.value,
    isFollowing: !authorInfo.value.isFollowing
  }).then((res) => {
    if (res.success) {
      authorInfo.value.isFollowing = !authorInfo.value.isFollowing
    } else {
      message.warning('请重试')
    }
  })
}

// 文件上传前检测
const beforeUpload = (data) => {
  if (data.file.file?.size > 10000000) {
    message.warning('请确保文件小于10MB')
    return false
  }
  return true
}

// 上传请求
const uploadFile = ({ file, id, _item }) => {
  const formData = new FormData()
  formData.append('file', file.file)
  api.Common.uploadFile(formData)
    .then((res) => {
      if (res.success) {
        api.Research.addFile({
          id,
          file: {
            fid: res.fid,
            url: res.url
          }
        }).then((_res) => {
          if (_res.success) {
            _item.file = {
              fid: res.fid,
              url: res.url
            }
            message.success('文件上传成功')
          }
        })
      } else {
        message.error('文件上传失败，请重试')
      }
    })
    .catch(() => {
      message.error('文件上传失败，请重试')
    })
}

// 申请文件
const askFile = (id) => {
  api.Research.askFile({ id }).then((res) => {
    if (res.success) {
      message.error('已向作者发送请求')
    } else {
      message.error('请求失败，请重试')
    }
  })
}

// 查看科研成果详情
const checkDetail = (id) => {
  window.open(`/research/detail/${id}`)
}

// 查看文件
const checkFile = (url) => {
  window.open(url)
}

// 查看用户详情
const checkAuthor = (id) => {
  router.push({ name: 'Profile', params: { id } })
}

// 私信
const toChat = () => {
  window.open(`/message/chat/${tmpUid.value}`, '_blank')
}

//项目申请
const apply = (id) => {
  api.Project.applyProject({ id }).then((res) => {
    if (res.success) {
      message.success('申请已发送，请等待审核')
    } else {
      message.error('申请发送失败，请重试')
    }
  })
}
</script>

<style scoped>
.follow-btn {
  margin-right: 1rem;
}
</style>
